<template>
  <el-form style="width: 100%">
    <el-row type="flex" justify="center">
      <el-form-item>
        <input size="large" type="file" id="files" name="image" @change="preview($event)" accept=".docx">
      </el-form-item>
    </el-row>

  <el-row >
    <el-form-item>
      <el-table
        :data="questions"
        max-height="460"
        >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
               <el-form-item>
                <span>{{ props.row.options && props.row.options[0] || "以上选项均不正确"}}</span>
              </el-form-item>
              <el-form-item>
                <span>{{ props.row.options && props.row.options[1] || "以上选项均不正确"}}</span>
              </el-form-item>
              <el-form-item>
                <span>{{ props.row.options && props.row.options[2] || "以上选项均不正确"}}</span>
              </el-form-item>
              <el-form-item>
                <span>{{ props.row.options && props.row.options[3]  || "以上选项均不正确"}}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column
          label="题号"
          prop="number">
        </el-table-column>
        <el-table-column
          label="内容"
          prop="content">
        </el-table-column>
        <el-table-column
          label="答案">
          <template slot-scope="scope">
            <span>{{scope.row && scope.row.answer && scope.row.answer.slice(scope.row.answer.indexOf('：') + 1)}}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
  </el-row>
  <el-row type="flex" justify="center">
    <el-button size="small" @click="downloadJson" :disabled="this.questions.length === 0">保存试题</el-button>
  </el-row>
</el-form>
</template>

<script>
export default {
    directives: {
  },
  components: {
  },
  data(){
      return {
        question: [
          {
            number: 0,
            content: '以下选项正确的是',
            options: ['A','B','C','D'],
            answer: 'B'
          }
        ],
        numberList: [
        ],
        input: 0,
        file: {
          size: 0,
          name: '',
          path: ''
        },
        questions: [
        ],
        map: {}
      }
  },
  watch: {
    questions: {
      handler: function (val, oldVal) {
        if (Array.isArray(val)) {
        }
      },
      deep: true
    }
  },
  created () {
  },
  methods: {
    downloadJson() {
      window.localStorage.setItem('questions',JSON.stringify(this.questions))
      window.localStorage.setItem('currentIndex',1)
      window.localStorage.setItem('maxIndex',this.questions.length)
      window.localStorage.setItem('errorIds',JSON.stringify(new Set()))


      // var FileSaver = require('file-saver')
      // let path = this.file.path.slice(0,-5)+'/'
      // var blob = new Blob([JSON.stringify(this.questions)], { type: "" });
      // FileSaver.saveAs(blob, this.file.name.slice(0,-5)+".json");
    },

    isContent (str){
      return !this.isNumber(str) && !this.isAnswer(str) && !this.isOption(str)
    },
    isNumber (str) {
      let isNumber = /^[\d]{1,5}、$/g
      return isNumber.test(str)
    },
      
    isAnswer (str) {
      let isAnswer = /^正确答案为：[ABCD]$/
      return isAnswer.test(str)
    },
    isOption(str){
      let isOption = /^[ABCD].*/
      return isOption.test(str)
    },
    preview(event){
      let file = document.getElementById('files').files[0]
      this.file = file
      const AdmZip = require('adm-zip')
      const localword = new AdmZip(file.path)
      // localword.extractAllTo(file.path.slice(0,-5)+'/',true)
      
      var contentXmlEntry = localword.getEntries().filter( x => x.entryName === 'word/document.xml')[0]
      var content = localword.readAsText(contentXmlEntry)
      var paragraphs = content.match(/<w:p.*?>.*?<\/w:p>/gi)

      let paragraphIndex = 0
      const map = new Map()
      if(paragraphs){
        // 筛选有内容的<w:p>（段落）
        paragraphs = paragraphs.filter(x => x.match(/<w:r>.*?<\/w:r>/gi))
        // 对每个段落，把段落内每个wt的内容拼接到一起
        paragraphs.forEach(paragraph => {
          let i = 0
          let finalWt = ''
          let wts = paragraph.match(/<w:t.*?>.*?<\/w:t>/gi)  //使用非贪婪匹配尽量切成更多段
          if(wts){
            wts.forEach(wt => {
              wt = wt.slice(5,-6)
              let index = wt.indexOf('>')
              wt = wt.slice(index+1)
              
              finalWt = finalWt + wt
            })
          }
          map.set(paragraphIndex,finalWt)
          paragraphIndex++
        })
      }
      this.map = map
      // 标准化题号和内容的顺序
      let size = this.map.size
      for(let i = 0; i < size - 1;i++){
        let current = this.map.get(i)
        let next = this.map.get(i+1)
        if(this.isContent(current) && this.isNumber(next)){
          let v = this.map.get(i+1)
          this.map.set(i+1,this.map.get(i))
          this.map.set(i,v)
        i = i-2
        }
      }
      for (let index = 0; index < this.map.size-1; index++) {
        if(this.isNumber(this.map.get(index)) && this.isAnswer(this.map.get(index +1))){
          let v = this.map.get(index - 1)
          this.map.set(index-1,this.map.get(index))
          this.map.set(index,v)
        }
      }
      // 构造试题
      for (let index = 0; index < this.map.size - 3; index++) {
        let question = {}
        question.options = []
        // 找题号
        if(!this.isNumber(this.map.get(index))){
          continue
        }

          let number = this.map.get(index)
          question.number = parseInt(number.slice(0,number.indexOf('、')))
          // 找内容
          if(!this.isContent(this.map.get(index+1))){
            continue
          }
            question.content = this.map.get(index+1)
            // 找答案
            if(this.isAnswer(this.map.get(index+2))){
              question.answer = this.map.get(index + 2).slice(this.map.get(index + 2).indexOf('：') + 1)
              // 找选项
              for (let optionIndex = 3; optionIndex < 7; optionIndex++) {
                if(this.isOption(this.map.get(index+optionIndex))){
                  let option = this.map.get(index+optionIndex)
                  question.options.push(option)
                }
              }
            }
        this.questions.push(question)
      }

      this.$message.success('添加试题完成！');
    }
  }
}
</script>
<style>
.demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>